package top.xtcoder.jdcbase.base.controller;

import java.awt.Color;
import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.nutz.lang.Lang;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import cn.hutool.captcha.generator.RandomGenerator;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

import org.springframework.web.bind.annotation.RestController;
import top.xtcoder.jdcbase.base.redis.RedisCache;
import top.xtcoder.jdcbase.base.redis.PrRedisKey;

@Api(tags = "验证码模块")
@RestController
@RequestMapping("/jdcbase/prbase/vrcode")
public class PrBaseVrcodeController {
	@Autowired
	private RedisCache redisCache;
	private Logger log = LoggerFactory.getLogger(PrBaseVrcodeController.class);
	
	@ApiOperation(value="获取验证码，直接访问")
	@GetMapping("/getVrcode")
	public void getVrcode(
			@ApiParam("时间戳")
			@RequestParam(name = "timestamp", defaultValue = "")
			String timestamp,
			HttpServletRequest req,
			HttpServletResponse resp) throws IOException{
		
		RandomGenerator randomGenerator = new RandomGenerator("123456789", 4);
		LineCaptcha c = CaptchaUtil.createLineCaptcha(200, 80, 4, 10);
		c.setGenerator(randomGenerator);
		c.setBackground(Color.decode("#E1E8F3"));
		String code = c.getCode();
		String key = PrRedisKey.PB_PHOTO_VRCODE(Lang.getIP(req) + timestamp);
		log.info("存一条=>" + key + ": " + code);
		redisCache.setCacheObject(key, code);
		c.write(resp.getOutputStream());
		resp.getOutputStream().flush();
		resp.getOutputStream().close();
	}
}

